



#Hardware Platform: FireBeetle-ESP32
#Result: input MQTTlibrary and remote controls LED by mqtt communication.

from umqtt.simple import MQTTClient
from machine import Pin
import network
import time
import dht
import _thread

SSID="Smart"
PASSWORD="123456788"

led=Pin(2, Pin.OUT, value=0)
d=dht.DHT11(Pin(25))

SERVER = "114.215.139.160"
CLIENT_ID = "espljh"
TOPIC = "led"
TOPIC1 = "hum"
TOPIC2 = "tem"

username='espljh'
password='ljh'
c=None
state = 0

def dht11():
  while(1):
    d.measure()
    print('temperature='+str(d.temperature()))
    print('humidity='+str(d.humidity()))
    c.publish('tem',str(d.temperature()))
    c.publish('hum',str(d.humidity()))
    time.sleep(2)

def sub_cb(topic, msg):
  global state
  print((topic, msg))
  if msg == b"1":
    led.value(1)
    state = 0
    print("1")
  elif msg == b"0":
    led.value(0)
    state = 1
    print("0")
  elif msg == b"toggle":
    # LED is inversed, so setting it to current state
    # value will make it toggle
    led.value(state)
    state = 1 - state
def connectWifi(ssid,passwd):
  global wlan
  wlan=network.WLAN(network.STA_IF)         #create a wlan object
  wlan.active(True)                         #Activate the network interface
  wlan.disconnect()                         #Disconnect the last connected WiFi
  wlan.connect(ssid,passwd)                 #connect wifi
  while(wlan.ifconfig()[0]=='0.0.0.0'):
    time.sleep(1)

    
#Catch exceptions,stop program if interrupted accidentally in the 'try'
try:
  connectWifi(SSID,PASSWORD)
  time.sleep(2)
  server=SERVER
  c = MQTTClient(CLIENT_ID,server,1883,username,password)     #create a mqtt client
  c.set_callback(sub_cb)                    #set callback
  c.connect()                               #connect mqtt
  time.sleep(2)
  c.subscribe(TOPIC)                        #client subscribes to a topic
  print("Connected to %s, subscribed to %s topic" % (server, TOPIC))
  _thread.start_new_thread(dht11,())

  while True:
    c.wait_msg()                            #wait message 
finally:
  if(c is not None):
    c.disconnect()
  wlan.disconnect()
  wlan.active(False)



